<?php 

namespace App\Controllers;
use Framework\Database;
use Framework\Validation;
use Framework\Session;
use Framework\Authorisation;
use Framework\Middleware\Authorise;


class ListingController{

    protected $db;


    public function __construct()
    {
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }

    /**
     * 展示所有岗位
     * 
     * @return void
     */
    public function index(){
        $listings=$this->db->query('SELECT * FROM listing ORDER BY created_at DESC')->fetchAll();


        loadView('listings/index',[
            'listings'=>$listings
        ]);
    }

    /**
     * 展示创建职位表单
     * 
     * @return void
     */

    public function create(){
        loadView('listings/create');
    }

    /**
     * 展示单一岗位页面
     * 
     * @return void
     */
    public function show($params){
        $id = $params['id'] ?? '';
        $params = [
            'id' =>$id
        ];
        $listing = $this->db->query('SELECT * FROM listing WHERE id=:id',$params)->fetch();
        
        //检查listing是否存在
        if(!$listing){
            ErrorController::notFound('该岗位不存在');
            return;
        }
        
        
        
        loadView('listings/show',[
            'listing'=>$listing
        ]);
    }


/**
 * 
 * @return void
 */
public function store(){
    $allowedFields = ['title','description','salary','tags',
        'company','address','city','phone','emial','requirements','benefits'];

        $newListingData = array_intersect_key($_POST,array_flip($allowedFields));

        //设置用户ID
        $newListingData['user_id']=Session::get('user')['id'];

        $newListingData =array_map('sanitize',$newListingData);

        $requiredFields = ['title','description','email','city','province'];

        $errors=[];

        foreach($requiredFields as $field){
            if(empty($newListingData[$field]) || !Validation::string($newListingData[$field])){
                $error[$field] = ucfirst($field) . '为必需项';
            }
        }

        if(!empty($errors)){
            loadView('listings/create',[
                'errors'=>$errors,
                'listing'=>$newListingData
            ]);
        }
        else{
            $fields = [];

            foreach($newListingData as $field=>$value){
                $fields[] = $field;
            }

            $fields = implode(',',$fields);

            $values=[];

            foreach($newListingData as $field=>$value){
                if($value === ''){
                    $newListingData[$field] =null;
                }
                $values[]= ':' . $field;
            }

            $values = implode(',',$values);

            $query = "INSERT INTO listing ({$fields}) VALUES ({$values})";

            Session::setFlashMessage('success_message','已成功创建职位！');


            $this->db->query($query,$newListingData);

            redirect('/listings');
        }
}

/**
 * 
 * @param array $params
 * @return void
 */
public function destory($params){
    $id = $params['id'];
    $params=[
        'id'=>$id
    ];
    $listing = $this->db->query('SELECT * FROM listing WHERE id = :id',$params)->fetch();

    if(!$listing){
        ErrorController::notFound('职位不存在');
        return;
    }

    if(!Authorisation::isOwner($listing->user_id)){
        inspect($_SESSION);
        Session::setFlashMessage('error_message','你没有权限删除此职位！');
        return redirect('/listings/' . $listing->id);
    }

    $this->db->query('DELETE FROM listing WHERE id =:id',$params);

    //设置提示信息
    Session::setFlashMessage('success_message','删除职位成功！');

    redirect('/listings');
}


/**
 * 
 * @param array $params
 * @return void
 */
public function edit($params){
    $id = $params['id'] ?? '';

    $params=[
        'id' => $id
    ];

    $listing = $this->db->query('SELECT * FROM listing WHERE id = :id',$params)->fetch();

    if(!$listing){
        ErrorController::notFound('职位不存在');
        return;
    }

    //授权
    if(!Authorisation::isOwner($listing->user_id)){
        Session::setFlashMessage('error_message','你没有权限修改此职位！');
        return redirect('/listings/' . $listing->id);
    }


    loadView('listings/edit',[
        'listing' =>$listing
    ]);
}

/**
 * @param array $params
 * @return void
 */
public function update($params){
    $id = $params['id'] ?? '';

    $params=[
        'id' => $id
    ];

    $listing = $this->db->query('SELECT * FROM listing WHERE id = :id',$params)->fetch();

    if(!$listing){
        ErrorController::notFound('职位不存在');
        return;
    }

    //授权
    if(!Authorisation::isOwner($listing->user_id)){
        Session::setFlashMessage('error_message','你没有权限修改此职位！');
        return redirect('/listings/' . $listing->id);
    }

    $allowedFields = ['title','description','salary','tags',
    'company','address','city','phone','emial','requirements','benefits'];
    
    $newListingData = array_intersect_key($_POST,array_flip($allowedFields));

    $newListingData['user_id'] = 1;

    $newListingData =array_map('sanitize',$newListingData);

    $requiredFields = ['title','description','email','city','province'];

    $errors=[];


    foreach($requiredFields as $field){
        if(empty($newListingData[$field]) || !Validation::string($newListingData[$field])){
            $error[$field] = ucfirst($field) . '为必需项';
        }
    }
    if(!empty($errors)){
        loadView('listings/create',[
            'errors'=>$errors,
            'listing'=>$newListingData
        ]);
    }
    else{
        $fields = [];

        foreach(array_keys($updateFields) as $field){
            $updateFields[] = "{$field} =:{$field}";
        }

        $updateFields = implode(',',$updateFields);

        $updateQuery = "UPDATE listing DET $updateFields WHERE id= :id";

        $updateValues['id'] = $id;


        $this->db->query($updateQuery,$updateValues);

       //设置成功信息
       Session::setFlashMessage('success_message','职位信息已更新！');

        redirect('/listings/' . $id);
    }
}

/**
     * 根据关键词和地点搜索列表
     * 此方法从请求中获取关键词和地点，然后执行数据库查询以找到匹配的列表项
     * 查询结果用于渲染列表视图
     * 
     * @return void 无返回值
     */
    public function search()
    {
        //从GET请求中获取关键词和地点
        $keywords=isset($_GET['keywords']) ? trim($_GET['keywords']) : '';
        $location=isset($_GET['location']) ? trim($_GET['location']) : '';

        //构建SQL查询
        $query="SELECT * FROM listing WHERE
        (title LIKE :keywords OR description LIKE :keywords OR
        tags LIKE :keywords OR company LIKE :keywords) AND
        (city LIKE :location OR province LIKE :location)";

        //准备查询参数
        $params=[
            'keywords'=>"%{$keywords}%",
            'location'=>"%{$location}%"
        ];

        //执行查询并获取所以匹配的记录
        $listings=$this->db->query($query,$params)->fetchAll();

        //加载列表视图
        loadView('/listings/index',[
            'listings'=>$listings,
            'keywords'=>$keywords,
            'location'=>$location
        ]);
    }

}

 ?>